package com.haier.cloudremote;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.haier.cloudremote.adapter.HDMIAdapter;
import com.haier.cloudremote.common.SLog;
import com.haier.cloudremote.common.StaticData;
import com.haier.cloudremote.common.TroubleShooting;
import com.haier.cloudremote.common.XmlParser;
import com.haier.cloudremote.model.HDMIInfo;
import com.haier.cloudremote.protocal.CAEProtocal;
import com.haier.cloudremote.protocal.TVProtocal;
import com.haier.cloudremote.util.FileUtil;

public class HDMIActivity extends Activity implements
	OnItemSelectedListener, OnItemClickListener{

	private StringBuffer debugBuffer = null;// 记录debug按键
	
	private static final int GET_CHANNEL_OK = 10001;
	private static final int GET_CHANNEL_FAIL = 10002;
	private static final int SET_CHANNEL_OK = 10003;
	private static final int SET_CHANNEL_FAIL = 10004;
	
	private ListView lvCommonListView;
	private ImageView selectImg;
	private LinearLayout layout;
	private TextView textView;
	
	private int gettedSignalId;
	private HDMIInfo checkedHDMI;
	private int gettedSourceId;
	
	private ArrayList<View> itemViews = new ArrayList<View>();
	private ArrayList<HDMIInfo> hdmiInfos = new ArrayList<HDMIInfo>();
	private int currSourceIndex;
	
	private Handler viewHandler;
	
	private Thread getChannelThread, setChannelThread;
	private Boolean isActivityAlive = true;
	
	private int check_margintop, item_height, checkitem_height, item_textsize, checkitem_textsize;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.hdmilayout);
		
		ActivityStackControlUtil.add(this); 
		
		viewInit();
		
		viewHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				int hdmiSize = hdmiInfos.size();
				HDMIInfo hdmiInfo;
				switch (msg.what) {				
				case GET_CHANNEL_OK:				
					for(int i=0;i<hdmiSize;i++){
						hdmiInfo = hdmiInfos.get(i);
						if(hdmiInfo.getHdmiId()==gettedSignalId){
							checkedHDMI = hdmiInfo;							
							lvCommonListView.setSelection(i);
							break;
						}
					}					

					break;
				case GET_CHANNEL_FAIL:
					for(int i=0;i<hdmiSize;i++){
						hdmiInfo = hdmiInfos.get(i);
						if(hdmiInfo.getHdmiId()==16){
							checkedHDMI = hdmiInfo;
							lvCommonListView.setSelection(i);
							break;
						}
					}				
					
					break;
				case SET_CHANNEL_OK:
					break;
				case SET_CHANNEL_FAIL:
					break;

				default:
					break;
				}
			}
			
		};	
		
		getSource();	
	}
	
	/**
	 * 获取信号源
	 */
	private void getSource() {
		// TODO Auto-generated method stub
//		TvEpgMidwareService  tvservice = new TvEpgMidwareService(this); 
//		String tvSourceType = tvservice.getTVSourceType();
		int source = TVProtocal.queryCurInputSrc(this);
		SLog.d("ssc", "tvSourceType=="+source);
		if(source!=0){
			int siginal_size = hdmiInfos.size();
			for(int i=0;i<siginal_size;i++){
			    if(source==hdmiInfos.get(i).getHdmiId()){
			        lvCommonListView.setSelection(i);
			        break;
			    }
			    if(hdmiInfos.get(i).getType().equals("YPBPR")){
			        lvCommonListView.setSelection(i);
			    }
			}
//			Toast.makeText(this, "信号源:"+source, Toast.LENGTH_SHORT).show();
		}else{
			viewHandler.sendEmptyMessage(GET_CHANNEL_FAIL);
		}
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SLog.d("ssc", "HDMIActivity---------onResume()");
		isActivityAlive = true;
		
	}



	/**
	 * 获取通道
	 */
	private void getChannel() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "获取通道");
		getChannelThread = new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int returnCode = CAEProtocal.getSSCState(2);
				SLog.d("ssc", "returnCode==" + returnCode);
				if (returnCode != -2000 && returnCode != 0) {
					gettedSignalId = returnCode;
					SLog.d("ssc", "gettedSignalId==" + gettedSignalId);
					viewHandler.sendEmptyMessage(GET_CHANNEL_OK);
				} else {
					viewHandler.sendEmptyMessage(GET_CHANNEL_FAIL);
				}

			}
			
		};
		getChannelThread.start();
	}
	
	private void setChannel() {
		// TODO Auto-generated method stub
		setChannelThread = new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int returnCode = 0;
				if (checkedHDMI != null) {
					 returnCode = CAEProtocal.setHDMI(checkedHDMI.getHdmiId());
					 SLog.d("ssc", "设过hdmi后，写配置文件 checkedHDMI=="+checkedHDMI.getHdmiId());
					 SLog.d("ssc", returnCode+"设置hdmi的返回值");
				}
				if (returnCode == 1001) {
					viewHandler.sendEmptyMessage(SET_CHANNEL_OK);
				} else {
					viewHandler.sendEmptyMessage(SET_CHANNEL_FAIL);

				}
				
			}
			
		};
		setChannelThread.start();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		SLog.d("ssc", "HDMIActivity---------onPause()");
		SLog.d("ssc", "在onPause中执行setChannel之前");
		setChannel();
		SLog.d("ssc", "在onPause中执行setChannel之后");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		SLog.d("ssc", "HDMIActivity---------onRestart()");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		SLog.d("ssc", "HDMIActivity---------onStart()");
		layout.setBackgroundResource(R.drawable.hdmibg);
	}

	/**
	 * 界面及控件初始化
	 */
	private void viewInit() {
		// TODO Auto-generated method stub
		
		check_margintop = (int) getResources().getDimension(R.dimen.list_check_margintop);
		item_height = (int)getResources().getDimension(R.dimen.list_item_height);
		checkitem_height = (int) getResources().getDimension(R.dimen.list_checkitem_height);
		item_textsize = (int) getResources().getDimension(R.dimen.list_item_textsize);
		checkitem_textsize = (int) getResources().getDimension(R.dimen.list_checkitem_textsize);
		
		lvCommonListView = (ListView) findViewById(R.id.hdmi_lvCommonListView);
		
		// 获取资源中的城市编码XML文件并对文件进行解析，获取到所有省市的列表
	    XmlResourceParser xrp = this.getResources().getXml(R.xml.signalsource); 

		adaptiveOfHDMI(XmlParser.getSignalList(xrp));
		
		lvCommonListView.setOnItemSelectedListener(this);
		lvCommonListView.setOnItemClickListener(this);
		
		selectImg = (ImageView) findViewById(R.id.hdmi_selectImg); 
		layout = (LinearLayout) findViewById(R.id.hdmilayout);
		
		Bitmap bm = FileUtil.readBitMap(this, R.drawable.hdmibg);
		layout.setBackgroundDrawable(new BitmapDrawable(bm));
	}

	/**
	 * 适配HDMI列表
	 * @param gettedSignalId2 
	 * @param arrayList 
	 */
	private void adaptiveOfHDMI(ArrayList<HDMIInfo> arrayList) {
		// TODO Auto-generated method stub
		HDMIInfo hdmiInfo;
		for(int i=0;i<arrayList.size();i++){
			SLog.d("ssc", "arrayList.get(i)(hdmiid,hdminame)"+arrayList.get(i).getHdmiId()+","+arrayList.get(i).getHdmiName());
		}
		
		for(int i=0;i<10;i++){// 先增加10个空的省
			hdmiInfo = new HDMIInfo();
			hdmiInfo.setHdmiId(-1);
			hdmiInfo.setHdmiName("");
			hdmiInfo.setType("");
			hdmiInfos.add(hdmiInfo);
		}
		int signalNum = arrayList.size();
		for(int i=0;i<signalNum;i++){
			hdmiInfos.add(arrayList.get(i));
		}
		
		for(int i=0;i<10;i++){// 先增加10个空的省
			hdmiInfo = new HDMIInfo();
			hdmiInfo.setHdmiId(-1);
			hdmiInfo.setHdmiName("");
			hdmiInfo.setType("");
			hdmiInfos.add(hdmiInfo);
		}
		HDMIAdapter adapter = new HDMIAdapter(this, hdmiInfos);
		lvCommonListView.setAdapter(adapter);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View v, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		SLog.d("ssc", "lvCommonListView.onItemSelected()");
		switch (arg0.getId()) {
		case R.id.hdmi_lvCommonListView:
			itemViews.add(v);
			if(arg2<=10){
				lvCommonListView.setSelectionFromTop(10, check_margintop);
				checkedHDMI = hdmiInfos.get(10);
//				checkedText = checkedHDMI.getHdmiName();
			}else if(arg2>hdmiInfos.size()-1-10){
				lvCommonListView.setSelectionFromTop(hdmiInfos.size()-1-10, check_margintop);
				checkedHDMI = hdmiInfos.get(hdmiInfos.size()-1-10);
//				checkedText = checkedHDMI.getHdmiName();
			}else{
				lvCommonListView.setSelectionFromTop(arg2, check_margintop);
				checkedHDMI = hdmiInfos.get(arg2);
//				checkedText = checkedHDMI.getHdmiName();
			}
			switch(checkedHDMI.getHdmiId()){
			case 1:
				selectImg.setImageResource(R.drawable.menu_signal_tv);
				break;
			case 2:				
			case 3:
				selectImg.setImageResource(R.drawable.menu_signal_av);
				break;
			case 4:
				selectImg.setImageResource(R.drawable.menu_signal_component);
				break;
			case 5:
				selectImg.setImageResource(R.drawable.menu_signal_pc);
				break;
			case 7:
			case 6:
				selectImg.setImageResource(R.drawable.menu_signal_hdmi);
				break;
			default:				
				break;
			}
			for(int i=0;i<itemViews.size();i++){
				if(itemViews.get(i)==v){
					SLog.d("test", "itemViews.get("+i+")==v");
					textView = (TextView) v.getTag();
					textView.setTextColor(Color.WHITE);
					textView.setTextSize(checkitem_textsize);
					textView.getLayoutParams().height = checkitem_height;
//					textView.setHeight(200);
				}else{
					textView = (TextView) itemViews.get(i).getTag();
					textView.setTextColor(Color.BLACK);
					textView.setTextSize(item_textsize);
					textView.getLayoutParams().height = item_height;
//					textView.setHeight(60);
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.hdmi_lvCommonListView:			
			
//			itemViews.add(v);
			if(arg2<=10){
//				lvCommonListView.setSelectionFromTop(10, 420);
				checkedHDMI = hdmiInfos.get(10);
//				checkedText = checkedHDMI.getHdmiName();
			}else if(arg2>hdmiInfos.size()-1-10){
//				lvCommonListView.setSelectionFromTop(hdmiInfos.size()-1-10, 420);
				checkedHDMI = hdmiInfos.get(hdmiInfos.size()-1-10);
//				checkedText = checkedHDMI.getHdmiName();
			}else{
//				lvCommonListView.setSelectionFromTop(arg2, 420);
				checkedHDMI = hdmiInfos.get(arg2);
//				checkedText = checkedHDMI.getHdmiName();
			}
			
			Intent intent = new Intent();
			intent.setClass(HDMIActivity.this, TestListViewActivity.class);
			startActivity(intent);

			break;
		default:
			break;
		}
	}

	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		SLog.d("ssc", "HDMIActivity---------onStop()");
		SLog.d("ssc", "写配置文件 checkedHDMI=="+checkedHDMI.getHdmiId());
		 // 写配置文件
		Editor sharedata = getSharedPreferences("ssc", Context.MODE_PRIVATE).edit(); 

		// 本次选择的省市区
		sharedata.putInt("checkedSourceId", checkedHDMI.getHdmiId());
		sharedata.commit(); 
       
       if(StaticData.checkedSource==null){
    	   StaticData.checkedSource = checkedHDMI;
       }
       
       
       layout.setBackgroundDrawable(null);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SLog.d("ssc", "HDMIActivity---------onDestroy()");
		 //移出管理栈
        ActivityStackControlUtil.remove(this);
        
        getChannelThread = null;
        setChannelThread = null;
        isActivityAlive = false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		SLog.d("ssc", "onKeyDown-----KeyCode()"+event.getKeyCode());
		SLog.d("ssc", "执行HDMIActivity");
		switch (event.getKeyCode()) {
		
//		SLog.d("ssc", "执行到switch");
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			SLog.d("ssc", "----------------------按向右键");
		case KeyEvent.KEYCODE_DPAD_CENTER:
			SLog.d("ssc", "----------------------按确认键");
			SLog.d("ssc", "执行前setChannel40020");
			setChannel();
			SLog.d("ssc", "执行后setChannel40020");
			Intent intent = new Intent();
			intent.setClass(HDMIActivity.this, TestListViewActivity.class);
			startActivity(intent);

			return false;
		case KeyEvent.KEYCODE_ENTER:
			SLog.d("ssc", "----------------------按键,这是实际的确认键");
		case KeyEvent.KEYCODE_DPAD_LEFT:
			finish();
			return false;
		case 12:// 5
			debugBuffer = new StringBuffer();
			debugBuffer.append("l");
			SLog.d("ssc", "11-----debugBuffer=="+debugBuffer);
			return false;

		case 13:// 6
			if(debugBuffer!=null){
				debugBuffer.append("o");
				SLog.d("ssc", "13-----debugBuffer=="+debugBuffer);
				return false;
			}
			break;

		case 11:// 4
			if(debugBuffer!=null){
				debugBuffer.append("g");
				TroubleShooting troubleShooting = new TroubleShooting(HDMIActivity.this, debugBuffer);
				debugBuffer = new StringBuffer();

				return false;
			}
			
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
}
